package cn.vastbase.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class TransactionExample {
    private static final String DB_URL = "jdbc:vastbase://192.168.56.11:5432/test";
    private static final String USER = "test";
    private static final String PASSWORD = "Vastdata#0730";

    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        try {
            // 连接数据库
            Class.forName("cn.com.vastbase.Driver");
            connection = DriverManager.getConnection(DB_URL, USER, PASSWORD);

            // 开启事务
            connection.setAutoCommit(false);

            // 执行数据库操作
            statement = connection.createStatement();
            // statement.execute("begin");

            //statement.executeQuery("select pg_sleep(30)");
            statement.execute("create event trigger sql_drop_command1 on sql_drop execute procedure drop_sql_command()");
            statement.executeUpdate("INSERT INTO users (name, email) VALUES ('John', 'john@example.com')");

            // 提交事务
            statement.execute("select 1 from users1");
            statement.executeQuery("select pg_sleep(30)");
//            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            // 回滚事务
//            try {
//                if (connection != null) {
//                    connection.rollback();
//                }
//            } catch (SQLException ex) {
//                ex.printStackTrace();
//            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
//finally {
        // 关闭连接和资源
        //          try {
        //    if (statement != null) {
        //        statement.close();
        //   }
        //            if (connection != null) {
        //                connection.close();
        //             }
        //       } catch (SQLException e) {
        //           e.printStackTrace();
        //       }
        //   }
    }
}
